<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2022-2099 李志刚（854378082@qq.com）
 * @Date: 2021-07-02 18:14:33
 * @Description: 文件上传用的接口，可直接传文件或者 base64 图片
 * @LastEditors: 李志刚
 * @LastEditTime: 2022-04-22 11:29:28
 * @FilePath: /CoinCMF/app/Http/Controllers/Common/FileController.php
 */

namespace App\Http\Controllers\Common;

use Illuminate\Http\Request;
use App\Customize\ImgCompression;
use App\Customize\Ueditor;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;

class FileController extends Controller
{
    // 文件形式上传
    public function postFile(Request $request)
    {
        try {
            // 支持的文件类型
            $isAllow = collect(['jpg', 'jpeg', 'gif', 'png', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'txt', 'rar', 'zip', 'swf', 'apk', 'mp4', 'mp3', 'avi']);
            // 默认大小
            $allSize = 100;
            // 验证是否有要上传的文件
            if (!$request->hasFile('imgFile')) {
                return $this->resJson(402, '文件不存在');
            }
            // 取得文件后缀
            $ext = $request->file('imgFile')->getClientOriginalExtension();
            // 检查文件类型
            if (!$isAllow->contains(strtolower($ext))) {
                $return['message'] = '不支持的图片类型!';
                return $this->resJson(402, '不支持的图片类型');
            }
            // 检查文件大小，不得大于3M
            $size = $request->file('imgFile')->getSize();
            if ($size > $allSize * 1073741824) {
                return $this->resJson(402, '单个文件不能大于' . $allSize . 'M');
            }
            // 生成文件名
            $filename = date('Ymdhis') . rand(100, 999);
            // 压缩缩略图图片，gif/png/jpeg全转为jpg格式
            if ($request->input('thumb',0)) {
                // 缩略图设置图片位置
                // 移动到新的位置，先创建目录及更新文件名为时间点
                $dir = public_path('/upload/thumb/' . date('Ymd') . '/');
                $localurl = '/upload/thumb/' . date('Ymd') . '/' . $filename . '.' . $ext;
            } else {
                // 移动到新的位置，先创建目录及更新文件名为时间点
                $dir = public_path('/upload/' . date('Ymd') . '/');
                $localurl = '/upload/' . date('Ymd') . '/' . $filename . '.' . $ext;
            }
            if (!file_exists($dir)) {
                mkdir($dir, 0755, true);
            }

            // 压缩缩略图图片，gif/png/jpeg全转为jpg格式
            if ($request->thumb) {
                // 缩略图设置图片位置
                // 移动到新的位置，先创建目录及更新文件名为时间点
                $dir = public_path('/upload/thumb/' . date('Ymd') . '/');
                if (!is_dir($dir)) {
                    Storage::disk('upload')->makeDirectory('upload/thumb/' . date('Ymd'));
                }
                // 如果是图片就开始压缩
                $tmpfile = $dir . $filename . '.' . $ext;
                // 压缩
                $thumbWidth = $request->input('thumbWidth', 1024);
                $thumbHeight = $request->input('thumbHeight', 0);
                // 保存文件
                Storage::disk('upload')->putFileAs('upload/' . date('Ymd'), $request->file('imgFile'), $filename . '.' . $ext);
                // 把压缩放到协程里边执行，不影响返回速度
                ImgCompression::compression($tmpfile, $thumbWidth, $thumbHeight);
                $localurl = '/upload/thumb/' . date('Ymd') . '/' . $filename . '.' . $ext;
            } else {
                // 移动到新的位置，先创建目录及更新文件名为时间点
                $dir = public_path('upload/' . date('Ymd') . '/');
                if (!is_dir($dir)) {
                    Storage::disk('upload')->makeDirectory('upload/' . date('Ymd'));
                }
                $isTrue = Storage::disk('upload')->putFileAs('upload/' . date('Ymd'), $request->file('imgFile'), $filename . '.' . $ext);
                $localurl = '/upload/' . date('Ymd') . '/' . $filename . '.' . $ext;
                // 如果是图片就开始压缩
                if (in_array($ext, ['jpg', 'jpeg', 'gif', 'png'])) {
                    $tmpfile = $dir . $filename . '.' . $ext;
                    // 压缩
                    $thumbWidth = $request->input('thumbWidth', 1024);
                    $thumbHeight = $request->input('thumbHeight', 0);
                    // 把压缩放到协程里边执行，不影响返回速度
                    ImgCompression::compression($tmpfile, $thumbWidth, $thumbHeight);
                }
            } 
            if (!$isTrue) {
                return $this->resJson(400, '服务器异常，请稍后再试', $isTrue);
            }
            $url = $localurl;
            return $this->resJson(200, '成功', ['url' => $url, 'filename' => $filename]);
        } catch (\Throwable $th) {
            return $this->resJson(500, '服务器异常，请稍后再试',$th->getMessage());
        }
    }
    // base64 形式上传
    public function postBase64(Request $request)
    {
        try {
            $image = $request->input('imgFile');
            $path = public_path('/upload/' . date('Ymd') . '/');
            //匹配出图片的格式
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $image, $result)) {
                $type = $result[2];
                if (!file_exists($path)) {
                    mkdir($path, 0700, true);
                }
                $file = $path . date('Ymdhis') . rand(100, 999) . "." . $type;
                if (file_put_contents($file, base64_decode(str_replace($result[1], '', $image)))) {
                    $file = str_replace(public_path(), '', $file);
                    // 把压缩放到协程里边执行，不影响返回速度
                    ImgCompression::compression($file, 1024,0);
                }
            }
            else {
                return $this->resJson(400, '不支持的图片类型');
            }
            return $this->resJson(200, '成功', ['url' => $file, 'filename' => $file]);
        } catch (\Throwable $th) {
            return $this->resJson(500, '服务器异常，请稍后再试');
        }
    }
    // 百度Ueditor文件上传功能
    public function getUeditorupload(Request $request)
    {
        header("Content-Type: text/html; charset=utf-8");
        error_reporting(E_ERROR);
        // 取配置内容
        $CONFIG = config('ueditor');
        // 看是哪个对应的功能
        $action = $request->action;
        switch ($action) {
            case 'config':
                $result =  json_encode($CONFIG);
                break;

                /* 列出图片 */
            case 'listimage':
                $result = $this->action_list($request, $CONFIG);
                break;
                /* 列出文件 */
            case 'listfile':
                $result = $this->action_list($request, $CONFIG);
                break;

                /* 抓取远程文件 */
            case 'catchimage':
                $result = $this->action_crawler($request, $CONFIG);
                break;

            default:
                $result = json_encode(array(
                    'state' => '请求地址出错'
                ));
                break;
        }

        /* 输出结果 */
        if (isset($request->callback)) {
            if (preg_match("/^[\w_]+$/", $request->callback)) {
                echo htmlspecialchars($request->callback) . '(' . $result . ')';
            } else {
                echo json_encode(array(
                    'state' => '返回参数不合法'
                ));
            }
        } else {
            echo $result;
        }
    }
    public function postUeditorupload(Request $request)
    {
        try {
            header("Content-Type: text/html; charset=utf-8");
            error_reporting(E_ERROR);
            // 取配置内容
            $CONFIG = config('ueditor');
            // 看是哪个对应的功能
            $action = $request->action;
            switch ($action) {
                    /* 上传图片 */
                case 'uploadimage':
                    /* 上传涂鸦 */
                case 'uploadscrawl':
                    /* 上传视频 */
                case 'uploadvideo':
                    /* 上传文件 */
                case 'uploadfile':
                    $result = $this->action_upload($request, $CONFIG);
                    break;

                    /* 抓取远程文件 */
                case 'catchimage':
                    $result = $this->action_crawler($request, $CONFIG);
                    break;

                default:
                    $result = json_encode(array(
                        'state' => '请求地址出错'
                    ));
                    break;
            }

            /* 输出结果 */
            if (isset($request->callback)) {
                if (preg_match("/^[\w_]+$/", $request->callback)) {
                    echo htmlspecialchars($request->callback) . '(' . $result . ')';
                } else {
                    echo json_encode(array(
                        'state' => '返回参数不合法'
                    ));
                }
            } else {
                echo $result;
            }
        } catch (\Throwable $th) {
            dd($th);
        }
    }
    // 上传文件
    private function action_upload($request, $CONFIG)
    {
        /* 上传配置 */
        $base64 = "upload";
        switch ($request->action) {
            case 'uploadimage':
                $config = array(
                    "pathFormat" => $CONFIG['imagePathFormat'],
                    "maxSize" => $CONFIG['imageMaxSize'],
                    "allowFiles" => $CONFIG['imageAllowFiles']
                );
                $fieldName = $CONFIG['imageFieldName'];
                break;
            case 'uploadscrawl':
                $config = array(
                    "pathFormat" => $CONFIG['scrawlPathFormat'],
                    "maxSize" => $CONFIG['scrawlMaxSize'],
                    "allowFiles" => $CONFIG['scrawlAllowFiles'],
                    "oriName" => "scrawl.png"
                );
                $fieldName = $CONFIG['scrawlFieldName'];
                $base64 = "base64";
                break;
            case 'uploadvideo':
                $config = array(
                    "pathFormat" => $CONFIG['videoPathFormat'],
                    "maxSize" => $CONFIG['videoMaxSize'],
                    "allowFiles" => $CONFIG['videoAllowFiles']
                );
                $fieldName = $CONFIG['videoFieldName'];
                break;
            case 'uploadfile':
            default:
                $config = array(
                    "pathFormat" => $CONFIG['filePathFormat'],
                    "maxSize" => $CONFIG['fileMaxSize'],
                    "allowFiles" => $CONFIG['fileAllowFiles']
                );
                $fieldName = $CONFIG['fileFieldName'];
                break;
        }

        /* 生成上传实例对象并完成上传 */
        $up = new Ueditor($fieldName, $config, $base64, $request);
        /**
         * 得到上传文件所对应的各个参数,数组结构
         * array(
         *     "state" => "",          //上传状态，上传成功时必须返回"SUCCESS"
         *     "url" => "",            //返回的地址
         *     "title" => "",          //新文件名
         *     "original" => "",       //原始文件名
         *     "type" => ""            //文件类型
         *     "size" => "",           //文件大小
         * )
         */
        $getInfo = $up->getFileInfo();
        // 添加成功以后，信息存储入数据库
        if ($getInfo['state'] == 'SUCCESS') {
            $data['filename'] = $getInfo['title'];
            $data['url'] = $getInfo['url'];
        }
        /* 返回数据 */
        return json_encode($getInfo);
    }
    // 列出图片
    private function action_list($request, $CONFIG)
    {
        /* 判断类型 */
        switch ($request->action) {
                /* 列出文件 */
            case 'listfile':
                $allowFiles = $CONFIG['fileManagerAllowFiles'];
                $listSize = $CONFIG['fileManagerListSize'];
                $path = $CONFIG['fileManagerListPath'];
                break;
                /* 列出图片 */
            case 'listimage':
            default:
                $allowFiles = $CONFIG['imageManagerAllowFiles'];
                $listSize = $CONFIG['imageManagerListSize'];
                $path = $CONFIG['imageManagerListPath'];
        }
        $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);

        /* 获取参数 */
        $size = isset($request->size) ? htmlspecialchars($request->size) : $listSize;
        $start = isset($request->start) ? htmlspecialchars($request->start) : 0;
        $end = $start + $size;

        /* 获取文件列表 */
        $path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "" : "/") . $path;
        $files = $this->getfiles($path, $allowFiles);
        if (!count($files)) {
            return json_encode(array(
                    "state" => "no match file",
                    "list" => array(),
                    "start" => $start,
                    "total" => count($files)
                ));
        }

        /* 获取指定范围的列表 */
        $len = count($files);
        for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--) {
            $list[] = $files[$i];
        }
        //倒序
        //for ($i = $end, $list = array(); $i < $len && $i < $end; $i++){
        //    $list[] = $files[$i];
        //}

        /* 返回数据 */
        $result = json_encode(array(
            "state" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => count($files)
        ));

        return $result;
    }
    /**
     * 遍历获取目录下的指定类型的文件
     * @param $path
     * @param array $files
     * @return array
     */
    private function getfiles($path, $allowFiles, &$files = array())
    {
        if (!is_dir($path)) return null;
        if (substr($path, strlen($path) - 1) != '/') $path .= '/';
        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . $file;
                if (is_dir($path2)) {
                    $this->getfiles($path2, $allowFiles, $files);
                } else {
                    if (preg_match("/\.(" . $allowFiles . ")$/i", $file)) {
                        $files[] = array(
                            'url' => substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])),
                            'mtime' => filemtime($path2)
                        );
                    }
                }
            }
        }
        return $files;
    }
    // 抓取远程图片
    private function action_crawler($request, $CONFIG)
    {
        set_time_limit(0);
        /* 上传配置 */
        $config = array(
            "pathFormat" => $CONFIG['catcherPathFormat'],
            "maxSize" => $CONFIG['catcherMaxSize'],
            "allowFiles" => $CONFIG['catcherAllowFiles'],
            "oriName" => "remote.png"
        );
        $fieldName = $CONFIG['catcherFieldName'];

        /* 抓取远程图片 */
        $list = array();
        $source = $request->$fieldName;
        foreach ($source as $imgUrl) {
            $item = new Ueditor($imgUrl, $config, "remote");
            $info = $item->getFileInfo();
            array_push($list, array(
                "state" => $info["state"],
                "url" => $info["url"],
                "size" => $info["size"],
                "title" => htmlspecialchars($info["title"]),
                "original" => htmlspecialchars($info["original"]),
                "source" => htmlspecialchars($imgUrl)
            ));
        }
        // 添加成功以后，信息存储入数据库
        if (count($list)) {
            // 循环出来可以插入的data
            $data = [];
            foreach ($list as $v) {
                $data[] = ['filename' => $v['title'], 'url' => $v['url']];
            }
        }
        /* 返回抓取数据 */
        return json_encode(array(
            'state' => count($list) ? 'SUCCESS' : 'ERROR',
            'list' => $list
        ));
    }
}
